#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>

void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel);

int main( int argc, char**argv)
{
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        return -1;
    }

    SDL_Surface* Surf_Display = NULL;

    if((Surf_Display = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL) {
        return -1;
    }

    int Running = 1;
    SDL_Event Event;
    SDL_PixelFormat *fmt = Surf_Display->format;

    Uint32 px = 0xFFFFFFFF;

    while(Running) {
        SDL_PollEvent(&Event);
        if(Event.type == SDL_QUIT) {
            Running = 0;
        }

        SDL_FillRect( Surf_Display, NULL, SDL_MapRGB( fmt, 0, 0, 255));

        if ( SDL_MUSTLOCK(Surf_Display) ) {
            if ( SDL_LockSurface(Surf_Display) < 0 ) {
                fprintf(stderr, "Can't lock Surf_Display: %s\n", SDL_GetError());
                return -1;
            }
        }

        putpixel(Surf_Display, 0, 50, px);

        if ( SDL_MUSTLOCK(Surf_Display) ) {
            SDL_UnlockSurface(Surf_Display);
        }

        SDL_Flip(Surf_Display);
    }

    SDL_Quit();

    return 0;
}


/*
 * Set the pixel at (x, y) to the given value
 * NOTE: The surface must be locked before calling this!
 */
void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to set */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    switch(bpp) {
    case 1:
        *p = pixel;
        break;

    case 2:
        *(Uint16 *)p = pixel;
        break;

    case 3:
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
            p[0] = (pixel >> 16) & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = pixel & 0xff;
        } else {
            p[0] = pixel & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = (pixel >> 16) & 0xff;
        }
        break;

    case 4:
        *(Uint32 *)p = pixel;
        break;
    }
}
